package msg

import (
	"reflect"
	"sync"
)

var mapMessage2Id = map[reflect.Type]uint16{}
var mapId2Message = map[uint16]reflect.Type{}
var registerRpcOnce sync.Once
var registerMsgOnce sync.Once

func RegisterRpcMessage(msgs map[uint16]reflect.Type) {
	registerRpcOnce.Do(func() {
		for k, v := range msgs {
			mapMessage2Id[v] = k
			mapId2Message[k] = v
		}
	})
}

func RegisterMessage(id2msg map[uint16]reflect.Type) {
	registerMsgOnce.Do(func() {
		for k, v := range id2msg {
			mapMessage2Id[v] = k
			mapId2Message[k] = v
		}
	})
}

func CheckMessage(typ reflect.Type) bool {
	if _, ok := mapMessage2Id[typ]; ok {
		return true
	}
	return false
}

func GetMessageId(typ reflect.Type) uint16 {
	if id, ok := mapMessage2Id[typ]; ok {
		return id
	}
	return 0
}

func GetMessageType(msgid uint16) reflect.Type {
	if typ, ok := mapId2Message[msgid]; ok {
		return typ
	}
	return nil
}
